/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package facade;

import java.util.ArrayList;
import local.ThemeFacadeLocal;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import model.Attempt;
import model.Attempt.SurveyStatus;
import model.Industry;
import model.Theme;
import model.ThemeScore;

/**
 *
 * @author karennyq
 */
@Stateless
public class ThemeFacade implements ThemeFacadeLocal {

    @PersistenceContext(unitName = "IEMPPU")
    private EntityManager em;

    @Override
    public Theme updateTheme(Long theme_id, String name, String short_desc, String firm_qns, String ind_qns) {
        Theme t = em.find(Theme.class, theme_id);
        t.setDescription(short_desc);
        t.setFirm_qns(firm_qns);
        t.setInd_qns(ind_qns);
        t.setName(name);
        em.merge(t);
        return t;
    }

    @Override
    public Theme getTheme(Long theme_id) {
        Theme t = em.find(Theme.class, theme_id);
        return t;
    }

    @Override
    public ArrayList<Theme> getThemes(Long industry) {
        ArrayList<Theme> tList = new ArrayList<Theme>();
        Industry i = em.find(Industry.class, industry);

        for (Theme t : i.getTheme()) {
            tList.add(t);
        }

        return tList;
    }

    @Override
    public Collection<Theme> findThemeByIndustry(Long industryId) {
        Industry in = em.find(Industry.class, industryId);
        ArrayList<Theme> ct = new ArrayList();
        for (Theme t : in.getTheme()) {
            t.setIndustry_id(industryId);
            ct.add(t);
        }
        return ct;
    }

    @Override
    public void edit(Theme t) {
        em.merge(t);
    }

    @Override
    public List<Collection<ThemeScore>> getThemeScoreList(String indID) {

        Long industryID = Long.parseLong(indID);
        String queryStr = "";
        Query query;
        queryStr = "SELECT a FROM Attempt a WHERE a.industry.ind_id=?1";

        query = em.createQuery(queryStr);
        query.setParameter(1, industryID);
        List<Collection<ThemeScore>> tsList = new ArrayList<Collection<ThemeScore>>();
        for (Object o : query.getResultList()) {
            Attempt a = (Attempt) o;
            if (a.getStatus().equals(SurveyStatus.Acceptable)) {
                tsList.add(a.getThemeScore());
            }

        }

        return tsList;
    }

    @Override
    public int getThemeScore(String rankType, String themeID, List<Collection<ThemeScore>> tsList) {

        int themeScoreResult = 0;
        List<Collection<ThemeScore>> themeScoreList = tsList;

        for (int i = 0; i < themeScoreList.size(); i++) {
            Collection<ThemeScore> tsCollection = themeScoreList.get(i);
            for (ThemeScore themeScore : tsCollection) {

                Long currentThemeID = themeScore.getTheme().getId();
                if (currentThemeID.toString().equalsIgnoreCase(themeID)) {
                    if ((rankType.equalsIgnoreCase("Firm")) && (themeScore.getFirm_score() != null)) {
                        themeScoreResult = themeScoreResult + themeScore.getFirm_score();

                    } else if ((rankType.equalsIgnoreCase("Industry")) && (themeScore.getInd_score() != null)) {
                        themeScoreResult = themeScoreResult + themeScore.getInd_score();
                    }
                }
            }
        }

        return themeScoreResult;
    }

    @Override
    public int getThemeResponse(String rankType, String themeID, List<Collection<ThemeScore>> tsList) {

        int themeResponseResult = 0;
        List<Collection<ThemeScore>> themeScoreList = tsList;

        for (int i = 0; i < themeScoreList.size(); i++) {
            Collection<ThemeScore> tsCollection = themeScoreList.get(i);
            for (ThemeScore themeScore : tsCollection) {

                Long currentThemeID = themeScore.getTheme().getId();
                if (currentThemeID.toString().equalsIgnoreCase(themeID)) {
                    if ((rankType.equalsIgnoreCase("Firm")) && (themeScore.getFirm_score() != null)) {
                        themeResponseResult++;

                    } else if ((rankType.equalsIgnoreCase("Industry")) && (themeScore.getInd_score() != null)) {
                        themeResponseResult++;
                    }
                }
            }
        }

        return themeResponseResult;
    }

    @Override
    public LinkedHashMap<String, Double> getThemeScoreTable(String indID, String rankType) {

        List<Collection<ThemeScore>> themeScoreList = getThemeScoreList(indID);
        HashMap<String, Double> themeScoreTable = new HashMap<String, Double>();

        Industry ind = em.find(Industry.class, Long.parseLong(indID));
        for (Theme theme : ind.getTheme()) {
            Long themeID = theme.getId();
            int themeScore = getThemeScore(rankType, themeID.toString(), themeScoreList);
            int themeResponse = getThemeResponse(rankType, themeID.toString(), themeScoreList);
            double themeChartScore = 0.00;
            if (themeResponse != 0) {
                themeChartScore = themeScore / themeResponse;
            }
            themeScoreTable.put(themeID.toString(), themeChartScore);
        }


        List mapKeys = new ArrayList(themeScoreTable.keySet());
        List mapValues = new ArrayList(themeScoreTable.values());
        Collections.sort(mapValues);
        Collections.sort(mapKeys);

        LinkedHashMap<String, Double> sortedMap = new LinkedHashMap<String, Double>();

        Iterator valueIt = mapValues.iterator();

        while (valueIt.hasNext()) {
            Object val = valueIt.next();
            Iterator keyIt = mapKeys.iterator();

            int counter = 0;
            while (counter < mapKeys.size()) {
                String key = keyIt.next().toString();
                String comp1 = themeScoreTable.get(key).toString();
                String comp2 = val.toString();

                if (comp1.equals(comp2)) {
                    themeScoreTable.remove(key);
                    mapKeys.remove(key);
                    sortedMap.put((String) key, (Double) val);
                    break;
                }
            }
        }
        return sortedMap;
    }

    @Override
    public double getAvgScore(String themeID, List<Collection<ThemeScore>> tsList) {

        double themeScoreResult = 0.00;
        List<Collection<ThemeScore>> themeScoreList = tsList;

        for (int i = 0; i < themeScoreList.size(); i++) {
            Collection<ThemeScore> tsCollection = themeScoreList.get(i);
            for (ThemeScore themeScore : tsCollection) {
                Long currentThemeID = themeScore.getTheme().getId();
                if ((currentThemeID.toString().equalsIgnoreCase(themeID)) && (themeScore.getAvg_score() != null)) {
                    themeScoreResult = themeScoreResult + themeScore.getAvg_score();
                }
            }
        }

        return themeScoreResult;
    }

    @Override
    public int getAvgScoreResponse(String themeID, List<Collection<ThemeScore>> tsList) {

        int themeResponseResult = 0;
        List<Collection<ThemeScore>> themeScoreList = tsList;

        for (int i = 0; i < themeScoreList.size(); i++) {
            Collection<ThemeScore> tsCollection = themeScoreList.get(i);
            for (ThemeScore themeScore : tsCollection) {
                Long currentThemeID = themeScore.getTheme().getId();
                if ((currentThemeID.toString().equalsIgnoreCase(themeID)) && (themeScore.getAvg_score() != null)) {
                    themeResponseResult++;
                }
            }
        }

        return themeResponseResult;
    }

    @Override
    public LinkedHashMap<String, Double> getThemeAvgScoreTable(String indID) {

        List<Collection<ThemeScore>> themeScoreList = getThemeScoreList(indID);
        LinkedHashMap<String, Double> themeScoreTable = new LinkedHashMap<String, Double>();

        Industry ind = em.find(Industry.class, Long.parseLong(indID));
        for (Theme theme : ind.getTheme()) {
            Long themeID = theme.getId();
            double themeAvgScore = getAvgScore(themeID.toString(), themeScoreList);
            int themeAvgResponse = getAvgScoreResponse(themeID.toString(), themeScoreList);
            double themeChartScore = 0.00;
            if (themeAvgResponse != 0) {
                themeChartScore = themeAvgScore / themeAvgResponse;
            }
            themeScoreTable.put(themeID.toString(), themeChartScore);
        }
        return themeScoreTable;
    }

    @Override
    public Theme find(Long theme_id) {
        return em.find(Theme.class, theme_id);
    }
}
